package aop;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Log;
import entity.Users;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import service.LogService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Map;

@Component  //对象由spring管理
@Aspect //切面注解
public class LogAspect {
    @Autowired
    private LogService logService;

    private static final Logger LOGGER = LogManager.getLogger(LogAspect.class);
    //定义切入点，切入到添加了LogData注解的方法上
    @Pointcut("@annotation(aop.LogData)")
    public void pointCut(){}

    /**
     * 记录日志的切面方法
     * 在该方法中定义统一的日志记录逻辑
     * @param joinPoint
     */
    @Before("pointCut()")
    public void log(JoinPoint joinPoint){
        //获取到方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取到连接点方法对象
        Method method = signature.getMethod();
        //获取方法上面特定的注解
        LogData annotation = method.getAnnotation(LogData.class);
        String description = annotation.description();

        //aop中获取request
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        /*Users users= (Users) session.getAttribute("users");
        String operation_Content= users+"执行了"+signature.getDeclaringTypeName()+"下的"+description+"操作!";*/

        Log log = new Log();
        log.setUser_id(2);
        log.setOperation(description);
       // log.setOperation_content(operation_Content);
        logService.insert(log);
    }
}
